'use client'

import { useState, useEffect } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Select, Form, FormField, FormItem, FormLabel } from '@/components/ui/form'
import { CheckCircle2, PlusCircle, Trash2, Edit3, Calendar, Clock, ArrowRight, ChevronDown } from 'lucide-react'
import { PieChart, Pie, Cell, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts'
import { Database } from '@/lib/supabase/types'
import { useRouter } from 'next/navigation'
import { format } from 'date-fns'

// 定义类型
type Goal = Database['public']['Tables']['therapeutic_goals']['Row']

export default function GoalsPage() {
  const [goals, setGoals] = useState<Goal[]>([])
  const [loading, setLoading] = useState(true)
  const [isAddingGoal, setIsAddingGoal] = useState(false)
  const [newGoal, setNewGoal] = useState<Partial<Goal>>({
    goal_title: '',
    goal_description: '',
    goal_category: 'emotional',
    current_progress: 0,
    status: 'active'
  })
  const [error, setError] = useState('')
  const supabase = createClient()
  const router = useRouter()

  // 目标类别选项
  const goalCategories = [
    { value: 'emotional', label: '情绪管理' },
    { value: 'relationship', label: '人际关系' },
    { value: 'self_esteem', label: '自尊自信' },
    { value: 'coping', label: '应对策略' },
    { value: 'other', label: '其他' },
  ]

  // 目标状态选项
  const goalStatuses = [
    { value: 'active', label: '进行中' },
    { value: 'completed', label: '已完成' },
    { value: 'paused', label: '暂停' },
    { value: 'archived', label: '已放弃' },
    { value: 'on_hold', label: '暂停(旧)' },
    { value: 'abandoned', label: '已放弃(旧)' }
  ]

  // 图表数据
  const getChartData = () => {
    const categoryCounts = goals.reduce((acc: Record<string, number>, goal) => {
      acc[goal.goal_category] = (acc[goal.goal_category] || 0) + 1
      return acc
    }, {})

    return Object.entries(categoryCounts).map(([name, value]) => ({
      name,
      value
    }))
  }

  const getProgressData = () => {
    return goals.map(goal => ({
      name: goal.goal_title.substring(0, 10) + '...',
      progress: goal.current_progress
    }))
  }

  // 颜色配置
  const COLORS = ['#86EFAC', '#93C5FD', '#FCA5A5', '#FB923C', '#A5B4FC']

  // 获取目标数据
  useEffect(() => {
    const fetchGoals = async () => {
      try {
        setLoading(true)
        // 在实际应用中，这里应该从数据库获取用户的目标数据
        // 此处为演示，使用模拟数据
        const mockGoals: Goal[] = [
          {
            id: '1',
            user_id: 'user123',
            goal_title: '管理焦虑情绪',
            goal_description: '学习识别焦虑触发因素并应用应对策略',
            goal_category: 'emotional',
            target_completion_date: '2023-12-31',
            current_progress: 65,
            success_metrics: { '焦虑发作频率': '减少50%', '应对策略使用率': '80%' },
            status: 'active',
            created_at: '2023-06-01T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          },
          {
            id: '2',
            user_id: 'user123',
            goal_title: '改善睡眠质量',
            goal_description: '建立规律的睡眠习惯，减少夜间醒来次数',
            goal_category: 'other',
            target_completion_date: '2023-11-30',
            current_progress: 40,
            success_metrics: { '睡眠时间': '7小时/晚', '睡眠质量评分': '7/10' },
            status: 'active',
            created_at: '2023-07-15T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          },
          {
            id: '3',
            user_id: 'user123',
            goal_title: '增强自信心',
            goal_description: '通过每日积极肯定和挑战消极思维来提高自尊',
            goal_category: 'self_esteem',
            target_completion_date: '2024-01-31',
            current_progress: 30,
            success_metrics: { '自我肯定实践': '每天2次', '消极思维识别率': '60%' },
            status: 'active',
            created_at: '2023-08-10T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          }
        ]

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        setGoals(mockGoals)
      } catch (error) {
        console.error('Error fetching goals:', error)
        setError('获取目标数据失败，请重试')
      } finally {
        setLoading(false)
      }
    }

    fetchGoals()
  }, [])

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!newGoal.goal_title || !newGoal.goal_description) {
      setError('目标标题和描述不能为空')
      return
    }

    try {
      setLoading(true)
      // 在实际应用中，这里应该将新目标保存到数据库
      const newGoalWithId = {
        ...newGoal,
        id: Date.now().toString(),
        user_id: 'user123', // 实际应用中应使用真实用户ID
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      } as Goal

      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      setGoals([...goals, newGoalWithId])
      setNewGoal({
        goal_title: '',
        goal_description: '',
        goal_category: 'emotional',
        current_progress: 0,
        status: 'active'
      })
      setIsAddingGoal(false)
      setError('')
    } catch (error) {
      console.error('Error adding goal:', error)
      setError('添加目标失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 处理删除目标
  const handleDeleteGoal = async (goalId: string) => {
    try {
      setLoading(true)
      // 在实际应用中，这里应该从数据库删除目标

      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      setGoals(goals.filter(goal => goal.id !== goalId))
      setError('')
    } catch (error) {
      console.error('Error deleting goal:', error)
      setError('删除目标失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 处理更新目标进度
  const handleUpdateProgress = async (goalId: string, progress: number) => {
    try {
      setLoading(true)
      // 在实际应用中，这里应该更新数据库中的目标进度

      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 300))

      setGoals(goals.map(goal => 
        goal.id === goalId ? { ...goal, current_progress: progress, updated_at: new Date().toISOString() } : goal
      ))
      setError('')
    } catch (error) {
      console.error('Error updating progress:', error)
      setError('更新进度失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-7xl mx-auto">
          <div className="text-center mb-10">
            <h1 className="text-3xl font-bold text-gray-900">进度目标</h1>
            <p className="mt-2 text-lg text-gray-600">加载目标数据中...</p>
          </div>
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto">
        <div className="text-center mb-10">
          <h1 className="text-3xl font-bold text-gray-900">进度目标</h1>
          <p className="mt-2 text-lg text-gray-600">管理和追踪你的治疗目标</p>
        </div>

        {error && (
          <div className="mb-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
            <strong className="font-bold">错误:</strong>
            <span className="block sm:inline"> {error}</span>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
          {/* 左侧面板 - 目标统计 */}
          <div className="lg:col-span-1 space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>目标概览</CardTitle>
                <CardDescription>你的目标分布和完成情况</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={getChartData()}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ name, percent = 0 }) => `${name} ${(percent * 100).toFixed(0)}%`}
                        outerRadius={80}
                        fill="#8884d8"
                        dataKey="value"
                      >
                        {getChartData().map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>进度分布</CardTitle>
                <CardDescription>各项目标的完成进度</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-64">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart
                      data={getProgressData()}
                      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                    >
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis domain={[0, 100]} label={{ value: '进度 (%)', angle: -90, position: 'insideLeft' }} />
                      <Tooltip />
                      <Bar dataKey="progress" fill="#86EFAC" name="完成进度" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 右侧面板 - 目标列表和添加表单 */}
          <div className="lg:col-span-2 space-y-6">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-semibold text-gray-900">我的目标</h2>
              <Button
                onClick={() => setIsAddingGoal(!isAddingGoal)}
                variant="default"
                className="flex items-center"
              >
                <PlusCircle className="mr-2 h-4 w-4" />
                {isAddingGoal ? '取消' : '添加新目标'}
              </Button>
            </div>

            {/* 添加目标表单 */}
            {isAddingGoal && (
              <Card>
                <CardHeader>
                  <CardTitle>添加新目标</CardTitle>
                </CardHeader>
                <CardContent>
                  <Form onSubmit={handleSubmit}>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <FormField
                        name="goal_title"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>目标标题</FormLabel>
                            <div>
                              <Input
                                type="text"
                                placeholder="输入目标标题"
                                value={newGoal.goal_title || ''}
                                onChange={(e) => setNewGoal({ ...newGoal, goal_title: e.target.value })}
                              />
                            </div>
                          </FormItem>
                        )}
                      />

                      <FormField
                        name="goal_category"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>目标类别</FormLabel>
                            <div>
                              <Select
                                options={goalCategories}
                                value={(newGoal.goal_category || 'emotional') as string}
                                onChange={(e) => setNewGoal({ ...newGoal, goal_category: e.target.value as any })}
                              />
                            </div>
                          </FormItem>
                        )}
                      />
                    </div>

                    <FormField
                      name="goal_description"
                      render={({ field }) => (
                        <FormItem className="mt-4">
                          <FormLabel>目标描述</FormLabel>
                          <div>
                              <Textarea
                                placeholder="详细描述你的目标..."
                                value={newGoal.goal_description || ''}
                                onChange={(e) => setNewGoal({ ...newGoal, goal_description: e.target.value })}
                                rows={3}
                              />
                            </div>
                        </FormItem>
                      )}
                    />

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                      <FormField
                        name="target_completion_date"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>目标完成日期</FormLabel>
                            <div>
                              <Input
                                type="date"
                                value={newGoal.target_completion_date || ''}
                                onChange={(e) => setNewGoal({ ...newGoal, target_completion_date: e.target.value })}
                              />
                            </div>
                          </FormItem>
                        )}
                      />

                      <FormField
                        name="status"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>目标状态</FormLabel>
                            <div>
                              <Select
                                options={goalStatuses}
                                value={(newGoal.status || 'active') as string}
                                onChange={(e) => setNewGoal({ ...newGoal, status: e.target.value as any })}
                              />
                            </div>
                          </FormItem>
                        )}
                      />
                    </div>

                    <div className="mt-6 flex justify-end">
                      <Button type="submit" variant="default" disabled={loading}>
                        保存目标
                      </Button>
                    </div>
                  </Form>
                </CardContent>
              </Card>
            )}

            {/* 目标列表 */}
            <div className="space-y-4">
              {goals.length === 0 ? (
                <Card>
                  <CardContent>
                    <div className="text-center py-8 text-gray-500">
                      <div className="text-lg font-medium">你还没有设置任何目标</div>
                      <Button
                        onClick={() => setIsAddingGoal(true)}
                        variant="outline"
                        className="mt-4"
                      >
                        <PlusCircle className="mr-2 h-4 w-4" />
                        添加第一个目标
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ) : (
                goals.map((goal) => (
                  <Card key={goal.id}>
                    <CardHeader className="flex justify-between items-center">
                      <div>
                        <CardTitle>{goal.goal_title}</CardTitle>
                        <CardDescription>{goal.goal_description}</CardDescription>
                      </div>
                      <div className="flex space-x-2">
                        <Button variant="ghost" size="sm" onClick={() => {/* 编辑目标逻辑 */}}>
                          <Edit3 className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => handleDeleteGoal(goal.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-4">
                        <div className="flex justify-between items-center">
                          <div className="flex items-center space-x-2">
                            <Calendar className="h-4 w-4 text-gray-500" />
                            <span className="text-sm text-gray-600">
                              目标日期: {goal.target_completion_date ? format(new Date(goal.target_completion_date), 'yyyy-MM-dd') : '未设置'}
                            </span>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Clock className="h-4 w-4 text-gray-500" />
                            <span className="text-sm text-gray-600">
                              最后更新: {format(new Date(goal.updated_at), 'yyyy-MM-dd HH:mm')}
                            </span>
                          </div>
                        </div>

                        <div>
                          <div className="flex justify-between mb-1">
                            <span className="text-sm font-medium text-gray-700">完成进度</span>
                            <span className="text-sm font-medium text-gray-700">{goal.current_progress}%</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2.5">
                            <div
                              className="bg-green-500 h-2.5 rounded-full"
                              style={{ width: `${goal.current_progress}%` }}
                            ></div>
                          </div>
                          <div className="flex justify-end mt-1">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleUpdateProgress(goal.id, Math.min(goal.current_progress + 10, 100))}
                            >
                              <ArrowRight className="h-3 w-3 mr-1" />
                              增加进度
                            </Button>
                          </div>
                        </div>

                        <div className="flex flex-wrap gap-2 mt-2">
                          <span className="px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-full">
                            {goalCategories.find(c => c.value === goal.goal_category)?.label || goal.goal_category}
                          </span>
                          <span className={`px-2 py-1 text-xs font-medium rounded-full ${goal.status === 'active' ? 'bg-green-100 text-green-800' : goal.status === 'completed' ? 'bg-gray-100 text-gray-800' : goal.status === 'paused' ? 'bg-yellow-100 text-yellow-800' : goal.status === 'archived' ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-800'}`}>
                            {goalStatuses.find(s => s.value === goal.status)?.label || goal.status}
                          </span>
                          {goal.current_progress === 100 && (
                            <span className="px-2 py-1 text-xs font-medium bg-purple-100 text-purple-800 rounded-full flex items-center">
                              <CheckCircle2 className="h-3 w-3 mr-1" />
                              已完成
                            </span>
                          )}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}